package org.atovio.servlet.config;

import jakarta.servlet.Filter;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.atovio.servlet.pk1.HelloServlet;
import org.atovio.servlet.pk2.LogFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

import java.io.IOException;

/**
 * @author AtoVio, Winter Yuan
 */
@Configuration
public class WebAppConfig {

    private ServletRegistrationBean<Servlet> servletProducer(Servlet servlet, String... urlMappings) {
        ServletRegistrationBean<Servlet> servletRegistration = new ServletRegistrationBean<>();
        servletRegistration.setServlet(servlet);
        servletRegistration.addUrlMappings(urlMappings);
        return servletRegistration;
    }

    private FilterRegistrationBean<Filter> filterProducer(Filter filter, int order, String... urlPatterns) {
        // 登记Filter对象
        FilterRegistrationBean<Filter> filterRegistration = new FilterRegistrationBean<>();
        filterRegistration.setFilter(filter);
        filterRegistration.addUrlPatterns(urlPatterns);
        filterRegistration.setOrder(order);
        return filterRegistration;
    }

    @Bean
    public ServletRegistrationBean<Servlet> getHelloServlet() {
        return servletProducer(new HelloServlet(),"/hello1");
    }

    @Bean
    public FilterRegistrationBean<Filter> getLogFilter() {
        return filterProducer(new LogFilter(), 1, "/*");
    }

    // 那么就可以使用匿名内部类的方式啦
    @Bean
    public ServletRegistrationBean<Servlet> getTestServlet() {
        return servletProducer(new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                resp.getWriter().println("Hello，this world");
            }
        }, "/test");
    }

    // 注册框架内部的Filter
    @Bean
    public FilterRegistrationBean<Filter> getCommonsRequestLoggingFilter() {
        CommonsRequestLoggingFilter commonsRequestLoggingFilter = new CommonsRequestLoggingFilter();
        // 记录uri地址？真的吗。确实，记录uri并包括查询的参数
        commonsRequestLoggingFilter.setIncludeQueryString(true);
        return filterProducer(commonsRequestLoggingFilter, 2, "/*");
    }

}
